<template>
  <div class="detection-basic-page">
    <el-card class="card-block breadcrumb-card">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>质量管理</el-breadcrumb-item>
        <el-breadcrumb-item>检测管理</el-breadcrumb-item>
        <el-breadcrumb-item>检测类型</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card class="filter-card card-block">
      <el-form :inline="true" :model="queryForm" label-width="auto">
        <el-form-item label="类型编号">
          <el-input v-model="queryForm.detectiontypecard" placeholder="请输入类型编号" clearable />
        </el-form-item>
        <el-form-item label="类型名称">
          <el-input v-model="queryForm.detectiontypename" placeholder="请输入类型名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.detectiontypestate" placeholder="请选择状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table-card card-block">
      <div class="toolbar">
        <el-button type="primary" @click="openDialog('create')">新增</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">删除</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="70" />
        <el-table-column prop="detectiontypename" label="检测类型名称" min-width="150" />
        <el-table-column prop="detectiontypecard" label="检测类型编码" min-width="150" />
        <el-table-column label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="row.detectiontypestate === '启用' ? 'success' : 'info'">
              {{ row.detectiontypestate }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="detectiontypedes" label="备注" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="openDialog('edit', row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :total="pagination.totalCount"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="520px" @close="handleDialogClose">
      <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px">
        <el-form-item label="类型编号" prop="detectiontypecard">
          <el-input v-model="formModel.detectiontypecard" placeholder="请输入类型编号" />
        </el-form-item>
        <el-form-item label="类型名称" prop="detectiontypename">
          <el-input v-model="formModel.detectiontypename" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="状态" prop="detectiontypestate">
          <el-radio-group v-model="formModel.detectiontypestate">
            <el-radio-button label="启用" />
            <el-radio-button label="禁用" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="detectiontypedes">
          <el-input v-model="formModel.detectiontypedes" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { reactive, ref, computed, onMounted } from "vue";
import https from "@/Http/http";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";

type ApiEnum = -1 | 0 | 1;

interface ApiPageingResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T;
}

interface DetectionTypeDTO {
  id: number;
  detectiontypecard: string;
  detectiontypename: string;
  detectiontypestate: string;
  detectiontypedes: string;
}

interface DetectionTypeRow extends DetectionTypeDTO {
  index: number;
}

const loading = ref(false);
const tableData = ref<DetectionTypeRow[]>([]);
const multipleSelection = ref<DetectionTypeRow[]>([]);

const statusOptions = [
  { label: "启用", value: "启用" },
  { label: "禁用", value: "禁用" },
];

const queryForm = reactive({
  detectiontypecard: "",
  detectiontypename: "",
  detectiontypestate: "",
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const dialogVisible = ref(false);
const dialogMode = ref<"create" | "edit">("create");
const formRef = ref<FormInstance>();
const formModel = reactive({
  id: undefined as number | undefined,
  detectiontypecard: "",
  detectiontypename: "",
  detectiontypestate: "启用",
  detectiontypedes: "",
});

const rules: FormRules = {
  detectiontypecard: [{ required: true, message: "请输入类型编号", trigger: "blur" }],
  detectiontypename: [{ required: true, message: "请输入类型名称", trigger: "blur" }],
};

const dialogTitle = computed(() => (dialogMode.value === "create" ? "新增检测类型" : "编辑检测类型"));

const fetchTableData = async () => {
  loading.value = true;
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<DetectionTypeDTO>>("/Detection/DetectionTypeList", {
      params: {
        pagesize: pagination.pageSize,
        pageindex: pagination.pageIndex,
        detectiontypecard: queryForm.detectiontypecard,
        detectiontypename: queryForm.detectiontypename,
        detectiontypestate: queryForm.detectiontypestate,
      },
    });
    if (data.code !== 1) {
      throw new Error(data.msg || "查询失败");
    }
    pagination.totalCount = data.totalCount || 0;
    tableData.value = (data.data || []).map((item, index) => ({
      ...item,
      index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1,
    }));
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || "获取检测类型失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.detectiontypecard = "";
  queryForm.detectiontypename = "";
  queryForm.detectiontypestate = "";
  handleQuery();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchTableData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page;
  fetchTableData();
};

const handleSelectionChange = (rows: DetectionTypeRow[]) => {
  multipleSelection.value = rows;
};

const resetForm = () => {
  formRef.value?.resetFields();
  formModel.id = undefined;
  formModel.detectiontypestate = "启用";
  formModel.detectiontypedes = "";
};

const openDialog = (mode: "create" | "edit", row?: DetectionTypeRow) => {
  dialogMode.value = mode;
  if (mode === "edit" && row) {
    formModel.id = row.id;
    formModel.detectiontypecard = row.detectiontypecard;
    formModel.detectiontypename = row.detectiontypename;
    formModel.detectiontypestate = row.detectiontypestate;
    formModel.detectiontypedes = row.detectiontypedes;
  } else {
    resetForm();
  }
  dialogVisible.value = true;
};

const handleDialogClose = () => {
  resetForm();
};

const buildPayload = () => ({
  id: formModel.id,
  detectiontypecard: formModel.detectiontypecard,
  detectiontypename: formModel.detectiontypename,
  detectiontypestate: formModel.detectiontypestate,
  detectiontypedes: formModel.detectiontypedes,
});

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    try {
      const payload = buildPayload();
      const request =
        dialogMode.value === "create"
          ? https.Writes.post<ApiResultResponse<number>>("/Detection/DetectionTypeAdd", payload)
          : https.Writes.put<ApiResultResponse<number>>("/Detection/DetectionTypeUpdate", payload);
      const { data } = await request;
      if (data.code !== 1) {
        throw new Error(data.msg || "保存失败");
      }
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      fetchTableData();
    } catch (error: any) {
      console.error(error);
      ElMessage.error(error.message || "保存失败");
    }
  });
};

const handleDelete = (row: DetectionTypeRow) => {
  ElMessageBox.confirm(`确认删除类型【${row.detectiontypename}】吗？`, "提示", { type: "warning" })
    .then(async () => {
      try {
        const res = await https.Writes.delete<ApiResultResponse<number>>("/Detection/DetectionTypeDel", {
          params: { id: row.id },
        });
        if (res.data.code !== 1) {
          throw new Error(res.data.msg || "删除失败");
        }
        ElMessage.success("删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条数据吗？`, "提示", { type: "warning" })
    .then(async () => {
      try {
        await Promise.all(
          multipleSelection.value.map((item) =>
            https.Writes.delete<ApiResultResponse<number>>("/Detection/DetectionTypeDel", {
              params: { id: item.id },
            }),
          ),
        );
        ElMessage.success("批量删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "批量删除失败");
      }
    })
    .catch(() => {});
};

onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
.detection-basic-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: linear-gradient(135deg, #f0f4ff 0%, #fef5f6 45%, #fdf8ff 100%);
}

.filter-card,
.table-card,
.card-block {
  width: 100%;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.9), rgba(237, 244, 255, 0.82));
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
  border-radius: 12px;
  backdrop-filter: blur(12px);
}

.toolbar {
  margin-bottom: 12px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>




